package com.xuzz.study.io.netty.rpc.consumer;

import com.xuzz.study.io.netty.rpc.base.RpcRequest;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.lang.reflect.Proxy;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author zhize.xu
 * @version 1.0
 * @ClassName:RpcConsumer
 * @Description:
 * @date 2018/11/27 16:29
 */
public class RpcConsumer {
    private static ExecutorService executor = Executors
            .newFixedThreadPool(Runtime.getRuntime().availableProcessors());

    private static HelloClientHandler client;

    /**
     * @return
     */
    public static Object choose(final Class<?> serviceClass)
    {
       return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
               new Class<?>[]{serviceClass},
               (proxy, method, args)->{
                    if(null==client)
                    {
                        initClient();
                    }

                   RpcRequest request=new RpcRequest();
                   request.setClassName(method.getDeclaringClass().getName());
                   request.setMethodName(method.getName());
                   request.setParams(args);

                   client.setPara(request);

                    return executor.submit(client).get();
                });
    }

    private static void initClient()
    {
        client = new HelloClientHandler();
        EventLoopGroup loopGroup = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(loopGroup)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY,true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel channel) throws Exception {
                        channel.pipeline().addLast(new StringDecoder());
                        channel.pipeline().addLast(new StringEncoder());
                        channel.pipeline().addLast(client);
                    }
                });
        try
        {
            bootstrap.connect("127.0.0.1",8080).sync();
        }
        catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
